#pragma once
#include<iostream>
#include<memory>
#include<string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include<cstring>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

static uint16_t default_port=8888;

enum{
    CREAT_ERR=1,
    BIND_ERR
};

class udp_sever
{
public:
    udp_sever(string ip,uint16_t port=default_port)
    :ip_(ip)
    ,port_(port)
    {
        std::cout << "server addr: " << ip << " : " << port_ << std::endl;
    }
    void Init()
    {
        sock_=socket(AF_INET,SOCK_DGRAM,0);//创建套接字
        if(sock_<0)
        {
            cerr<<"创建失败！"<<strerror(errno)<<endl;
            exit(CREAT_ERR);
        }
        cout<<"ip_: "<<ip_<<" port_: "<<port_<<endl;
        struct sockaddr_in local;
        bzero(&local,sizeof(local));//初始化结构体，方便重新赋值
        local.sin_family=AF_INET;//进行网络通信
        local.sin_port=htons(port_);//转换成网络字节序
        local.sin_addr.s_addr=inet_addr(ip_.c_str());
       // int bindRet=bind(sock_,(sockaddr*)&local,sizeof(local));//把套接字绑定到网络上
        if(bind(sock_,(sockaddr*)&local,sizeof(local))<0)
        {
            cerr<<"绑定失败！: "<<strerror(errno)<<endl;
            exit(BIND_ERR);
        }
        cout<<"绑定成功，可以开始通信！"<<endl;


    }
    void Start()
    {
        
    }
    ~udp_sever()
    {}
private:
    string ip_;
    int sock_;
    uint16_t port_;


};